//
//  AppleScriptNotifier.m
//  Cidney
//
//  Created by Chris Karr on 3/20/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "AppleScriptNotifier.h"
#import "Dispatcher.h"
#import <AddressBook/AddressBook.h>
#import <Carbon/Carbon.h>

#define SCRIPT_PATH [NSString stringWithFormat:@"%@/Library/Application Support/Cidney/AppleScript", NSHomeDirectory ()]

@implementation AppleScriptNotifier

- (void) awakeFromNib
{
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(update:) name:INCOMING_CALL object:nil];
}

- (void) update: (NSNotification *) msg
{
	NSDictionary * userInfo = [msg userInfo];
	
	ABPerson * person = [userInfo valueForKey:PERSON_KEY];
	
	NSString * name = [userInfo valueForKey:NAME_KEY];
	NSString * number = [userInfo valueForKey:NUMBER_KEY];
	NSString * abId = @"";

	if (person != nil)
	{
		name = [NSString stringWithFormat:@"%@ %@", [person valueForProperty:kABFirstNameProperty], [person valueForProperty:kABLastNameProperty]];

		if ([[person valueForProperty:kABPersonFlags] boolValue])
			name = [person valueForProperty:kABOrganizationProperty];
			
		abId = [person valueForProperty:kABUIDProperty];
	}
	
	NSFileManager * fm = [NSFileManager defaultManager];
	BOOL isDir = NO;

	if ([fm fileExistsAtPath:SCRIPT_PATH isDirectory:&isDir] && isDir)
	{
		NSArray * files = [[fm directoryContentsAtPath:SCRIPT_PATH] sortedArrayUsingSelector:@selector(compare:)];
		
		for (NSString * file in files)
		{
			if ([file hasSuffix:@".scpt"])
			{
				NSDictionary * errors = [NSDictionary dictionary];
				NSURL * scriptUrl = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", SCRIPT_PATH, file]];
					
				NSAppleScript * scpt = [[NSAppleScript alloc] initWithContentsOfURL:scriptUrl error:nil];
					
				if (scpt != nil)
				{
					NSAppleEventDescriptor * asName = [NSAppleEventDescriptor descriptorWithString:name];
					NSAppleEventDescriptor * asNumber = [NSAppleEventDescriptor descriptorWithString:number];
					NSAppleEventDescriptor * asId = [NSAppleEventDescriptor descriptorWithString:abId];

					NSAppleEventDescriptor * parameters = [NSAppleEventDescriptor listDescriptor];
					[parameters insertDescriptor:asName atIndex:1];
					[parameters insertDescriptor:asNumber atIndex:2];
					[parameters insertDescriptor:asId atIndex:3];

					ProcessSerialNumber psn = { 0, kCurrentProcess };
					NSAppleEventDescriptor * target = [NSAppleEventDescriptor descriptorWithDescriptorType:typeProcessSerialNumber
															bytes:&psn
															length:sizeof(ProcessSerialNumber)];

					NSAppleEventDescriptor *handler = [NSAppleEventDescriptor descriptorWithString:@"incoming_call"];

					NSAppleEventDescriptor *event = [NSAppleEventDescriptor appleEventWithEventClass:kASAppleScriptSuite
															eventID:kASSubroutineEvent
															targetDescriptor:target
															returnID:kAutoGenerateReturnID
															transactionID:kAnyTransactionID];

					[event setParamDescriptor:handler forKeyword:keyASSubroutineName];
					[event setParamDescriptor:parameters forKeyword:keyDirectObject];

					[scpt executeAppleEvent:event error:&errors];
					[scpt release];
				}
			}
		}
	}
	else
		[fm createDirectoryAtPath:SCRIPT_PATH withIntermediateDirectories:YES attributes:nil error:nil];
}

@end
